package betfc

import (
	"net/http"
	"strings"
	"io/ioutil"
	"time"
	"strconv"
	"net/url"
	"tidwall/gjson"
	"betdata"
	"common"
	"fmt"
)

//重庆时时彩 02:00:00~~10:00:00 凌晨2点到早上10点这个时间段不开奖
func GetSccBetMap() {
	defer GetSccBetMap()
	timeNow := time.Now().Unix()
	timeStr1 := time.Now().Format("2006-01-02") + " 02:00:10"    //每天的封盘时间,加个十秒让其能获取到最后一期的结果
	sTime,_ := time.Parse("2006-01-02 15:04:05",timeStr1)
	sTimeNnix := sTime.Unix()
	timeStr2 := time.Now().Format("2006-01-02") + " 10:00:00"    //每天的开盘时间
	eTime,_ := time.Parse("2006-01-02 15:04:05",timeStr2)
	eTimeNnix := eTime.Unix()
	if timeNow < sTimeNnix || timeNow > eTimeNnix{      //每天的开盘时间内
		betMap, sleepTime,period := SscServer()
		if sleepTime >= 0 {
			time.Sleep(time.Duration(sleepTime+1) * time.Second)
			return
		} else if sleepTime < 0 {
			betdata.WrightFile(period,"ssc",betMap)    // todo 将数据写入到对应的配置文件中
			time.Sleep(time.Duration(140) * time.Second)    //封盘倒计时
			return
		}
	}else if timeNow >= sTimeNnix && timeNow <= eTimeNnix{
		time.Sleep(time.Duration(eTimeNnix-timeNow) * time.Second)
		return
	}
}

//玩法参数
type SscPlayStruct struct {
	Handicap    string `json:"handicap"`
	BuhuoStatus string `json:"buhuoStatus"`
	Play        string `json:"play"`
}

//重庆时时彩 一种玩法一次性获取 凌晨2点到早上10点这个时间段不开奖 todo 接收cookie并替换 sysinfo=ssc%7C0%7Ca%7C0%7C0;
func SscServer() (map[string]int, int,string) {
	betMap := make(map[string]int)
	var sleeptime int
	var period string
	q := url.Values{}
	q.Set("handicap", "A")
	q.Set("buhuoStatus", "1")
	//body := ioutil.NopCloser(strings.NewReader(q.Encode()))
	client := &http.Client{}
	tUnix := time.Now().UnixNano() / 1e6
	strAjax := strconv.Itoa(int(tUnix)) + "__ajax"
	req, _ := http.NewRequest("POST", "http://tc6.x.l11ll.ninja/sscat35657c_232/ssc/monitor/ajax/?&_="+strAjax, strings.NewReader(q.Encode()))

	cookieString := common.GetCookies()
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	for _,value := range cookieString {
		req.AddCookie(&value)
	}
	ck:=new(http.Cookie)
	ck.Name = "sysinfo"
	ck.Value = "ssc%7C0%7Ca%7C0%7C0"
	req.AddCookie(ck)
	resp, _ := client.Do(req)
	defer resp.Body.Close()
	result, _ := ioutil.ReadAll(resp.Body)
	arr := strings.Split(string(result), "êêê") //切割字符串
	fmt.Println("ssc:",string(result))
	state := gjson.Get(arr[0], "data.betnotice.timeclose") //封盘倒计时
	timesnow := gjson.Get(arr[0], "data.betnotice.timesnow") //期数
	betData := gjson.Get(arr[0], "data.supervision")       //下注内容
	period = timesnow.Str
	sleeptime = int(state.Int())
	if sleeptime > 0 { //未封盘
		return betMap, sleeptime,period
	} else if sleeptime < 0 {
		betRange := betData.Map()
		for k, v := range betRange {
			temp := v.Raw
			temp= strings.Replace(temp,"\"","",-1)
			arr := strings.Split(temp, ",")
			betNum, _ := strconv.Atoi(arr[1])
			if betNum > 0 {
				betMap[k] = betNum
			}
		}
	}
	return betMap, sleeptime,period
}
